<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2018/8/19
 * Time: 14:33
 */

namespace app\mec\controller;


use think\Db;
use think\Request;
use app\mec\model\Classroom as ClassroomModel;//课程
use app\mec\model\ClassroomType as ClassroomTypeModel;//课程分类
use app\mec\model\AboutUs as AboutUsModel;//关于我们
use app\mec\model\ClassroomCatalogue as ClassroomCatalogueModel;//课程章节

use Qiniu\Auth;// 引入鉴权类
use Qiniu\Storage\UploadManager;// 引入上传类
use Qiniu\Processing\PersistentFop;
require_once('../extend/qiniu/autoload.php');

class Classroom extends Base
{
    /**
     * 课程列表
     * @return mixed|\think\response\Json
     */
    public function index(){
        $classroomModel = new ClassroomModel();
        if(Request::instance()->isAjax()){
            $params = input('param.');
            $where = [];
            //机构名称模糊查询
            if(isset($params['key']) && $params['key'] != '')
            {
                $where['uc.classroom_title|um.mechanism_name'] = ['like', "%" . $params['key'] . "%"];
            }
            //审核状态
            if(isset($params['classroom_status']) && $params['classroom_status'] != 0){
                $where['uc.classroom_status'] = $params['classroom_status'];
            }
            $where['uc.mechanism_id'] = session('mmid');
            $page = input('page') ? input('page') : 1;
            $limits = input('limit') ? input('limit') : 10;// 获取总条数;
            $field = 'uc.id, uc.classroom_title, uc.classroom_img, uct.classroom_name as typeName, uc.classroom_price, 
            uc.create_admin_id, uc.classroom_status, um.mechanism_name';
            $lists = $classroomModel->classroomLists($where, $field, $page, $limits);
            $count = $classroomModel->getCount($where);
            foreach($lists as $key=>&$list){
                //统计总的章节数
                $num = Db::table('up_classroom_catalogue')->where('classroom_id', $list['id'])->count();
                $list['catalogueNum'] = $num;
                //是否是当前登录者发布，如果是，则置1
                if($list['create_admin_id'] == session('uid')){
                    $list['ifSelf'] = 1;
                }else{
                    $list['ifSelf'] = 0;
                }
            }
            return json(['code'=>0,'msg'=>'','count'=>$count,'data'=>$lists]);
        }
        if(session('?classroom_id')){
            session('classroom_id',null);
        }
        return $this->fetch('classroom/index');
    }
    
    /**
     * 添加课程
     * @return array|mixed
     */
    public function classroomAdd(){
        $classroomModel = new ClassroomModel();
        $classroomTypeModel = new ClassroomTypeModel();
        $aboutUsModel = new AboutUsModel();
        $value = 'price_button';
        $price_button = $aboutUsModel->getValue($value);//价格开关
        if(Request::instance()->isAjax()){
            $params = input('param.');
            if($params['classroom_id'] == ''){
                return ['code' => 100, 'data' => '', 'msg' => '请选择课程分类'];
            }
            $data = [
                'classroom_title' => $params['classroom_title'],//课程标题
                'classroom_content' => $params['content'],//课程详情
                'classroom_img' => $params['images'],//缩略图
                'classroom_id' => $params['classroom_id'],//所属分类
                'mechanism_id' => session('mmid'),//发布机构ID
                'create_time' => date('Y-m-d H:i:s'),//发布时间
                'big_img' => $params['photo'],//课程大图
                'create_admin_id' => session('mid'),//发布者
            ];
            if($price_button == 1){//价格开关打开
                $data['classroom_cate'] = $params['classroom_cate'];
                if($params['classroom_cate'] == 1){//免费
                    $data['classroom_price'] = 0;
                }else{//付费
                    $data['classroom_price'] = $params['classroom_price'];
                }
            }else{
                $data['classroom_cate'] = 1;
                $data['classroom_price'] = 0;
            }
            $result = $classroomModel->insertClassroom($data);
            if($result){
                return ['code' => 200, 'data' =>"", 'msg' => '添加课程成功'];
            }else{
                return ['code' => 100, 'data' => '', 'msg' => '添加课程失败'];
            }
        }
        $typeLists = $classroomTypeModel->getTypeInfo();//课程分类名称、ID
        $this->assign([
            'typeLists' => $typeLists,
            'price_button' => $price_button
        ]);
        return $this->fetch('classroom/classroomadd');
    }
    
    /**
     * 图片删除
     * @return \think\response\Json
     */
    public function deleteImg(){
        $add  = input('add');
        $url =  "http://".$_SERVER['HTTP_HOST'].'/';
        $add = str_replace ($url,'',$add);
        if(unlink($add)){
            return json(['code'=>200,'msg'=>'删除成功！']);
        }else{
            return json(['code'=>100,'msg'=>'删除失败！']);
        }
    }
    
    /**
     * 编辑课程
     * @return mixed
     */
    public function classroomEdit(){
        $classroomModel = new ClassroomModel();
        $classroomTypeModel = new ClassroomTypeModel();
        $aboutUsModel = new AboutUsModel();
        $value = 'price_button';
        $price_button = $aboutUsModel->getValue($value);//价格开关
        if(Request::instance()->isAjax()){
            $params = input('param.');
            $data = [
                'classroom_title' => $params['classroom_title'],//课程标题
                'classroom_content' => $params['content'],//课程详情
//                'classroom_img' => $params['images'],//缩略图
                'classroom_id' => $params['classroom_id'],//所属分类
                'big_img' => $params['photo'],//课程大图
                'classroom_status' => 1,//编辑后，重新提交审核
            ];
            if($price_button == 1){//价格开关打开
                $data['classroom_cate'] = $params['classroom_cate'];
                if($params['classroom_cate'] == 1){//免费
                    $data['classroom_price'] = 0;
                }else{//付费
                    $data['classroom_price'] = $params['classroom_price'];
                }
            }else{
                $data['classroom_cate'] = 1;
                $data['classroom_price'] = 0;
            }
            if(!empty($params['images'])){
                $data['classroom_img'] = $params['images'];
            }
            $res = $classroomModel->updateClassroom($params['id'], $data);
            if($res){
                return ['code' => 200, 'data' =>"", 'msg' => '编辑成功'];
            }else{
                return ['code' => 100, 'data' => '', 'msg' => '编辑失败'];
            }
        }
        $param = input('param.');
        $where['id'] = $param['id'];
        $field = 'id, classroom_title, classroom_img, classroom_id, classroom_price, classroom_cate, 
        classroom_content, big_img';
        $lists = $classroomModel->getInfo($where, $field);
        $typeLists = $classroomTypeModel->getTypeInfo();//课程分类名称、ID
        $this->assign([
            'typeLists' => $typeLists,
            'price_button' => $price_button,
            'lists' => $lists
        ]);
        return $this->fetch('classroom/classroomedit');
    }
    
    /**
     * 查看课程介绍
     * @return mixed
     */
    public function classroomInfo(){
        $param = input('param.');
        $classroomModel = new ClassroomModel();
        $field = 'classroom_content';
        $where = [];
        $where['id'] = $param['id'];
        $info = $classroomModel->getInfo($where, $field);
        $this->assign('info', $info);
        return $this->fetch('classroom/classroominfo');
    }
    
    /**
     * 课程审核、查看审核
     * @return array|mixed
     */
    public function classroomAudit(){
        $classroomModel = new ClassroomModel();
        $param = input('param.');
        if(Request::instance()->isAjax()){
            $params = input('param.');
            $data = [];
            if($params['classroom_status'] == 2){//审核通过
                $data = [
                    'classroom_status' => $params['classroom_status'],
                ];
            }
            if($params['classroom_status'] == 3){//审核不通过
                $data = [
                    'classroom_status' => $params['classroom_status'],
                    'classroom_false_reason' => $params['classroom_false_reason'],
                ];
            }
            $res = $classroomModel->updateClassroom($params['id'], $data);
            if($res){
                return ['code' => 200, 'data' =>"", 'msg' => '审核成功'];
            }else{
                return ['code' => 100, 'data' => '', 'msg' => '审核失败'];
            }
        }
        $field = 'uc.id, uc.classroom_title, uc.classroom_img, uc.classroom_price, uc.classroom_status, 
        uc.classroom_false_reason, uc.classroom_content, uct.classroom_name';
        $info = $classroomModel->classroomAudit($param['id'], $field);
        $this->assign('info', $info);
        return $this->fetch('classroom/classroomaudit');
    }
    
    /**
     * 课程章节列表
     * @return mixed|\think\response\Json
     */
    public function classroomcatalogue(){
        $classroomModel = new ClassroomModel();
        $classroomCatalogueModel = new ClassroomCatalogueModel();
        if(Request::instance()->isAjax()){
            $params = input('param.');
            $page = input('page') ? input('page') : 1;
            $limits = input('limit') ? input('limit') : 10;// 获取总条数;
            $lists = Db::table('up_classroom_catalogue')->where('classroom_id', $params['id'])
                ->order('catalogue_id')
                ->page($page, $limits)
                ->select();
            $count = $classroomCatalogueModel->getCount($params['id']);
            return json(['code'=>0,'msg'=>'','count'=>$count,'data'=>$lists]);
        }
        $param = input('param.');
        if(!session('?classroom_id')){
            session('classroom_id',$param['id']);
        }
        return $this->fetch('classroom/classroomcatalogue');
    }
    
    /**
     * 添加课程章节
     * @return array|mixed
     */
    public function catalogueAdd(){
        set_time_limit (0);
        if(Request::instance()->isAjax()){
            $params = input('param.');
            $filePath = $_SERVER['DOCUMENT_ROOT']. DS . $params['photo'];
            $qnInfo = $this->videoQN($filePath);
            if($qnInfo){
                $this->zhuanma($qnInfo['key']);
            }
            $time = explode('.', $qnInfo['vtime']);
            $fen = floor($time[0]/60);
            $miao = floor(($time[0]-$fen*60)%60);
            
            $data = [
                'catalogue_title' => $params['catalogue_title'],//标题
                'catalogue_img' => $params['images'],//缩略图
                'catalogue_url' => "http://qiniu.verynurse.com/" . "h264_" . $qnInfo['key'],//视频
                'classroom_id' => session('classroom_id'),//课程ID
                'create_time' => date('Y-m-d H:i:s'),//创建时间
                'catalogue_time' => $fen . ':' . $miao//视频时长
            ];
            $classroomCatalogueModel = new ClassroomCatalogueModel();
            $res = $classroomCatalogueModel->insertCatalogue($data);
            if($res){
                @unlink($filePath);//删除本地文件
                $classroomModel = new ClassroomModel();
                //添加课程章节，需重新提交审核
                $classroomModel->updateClassroom(session('classroom_id'), ['classroom_status'=>1]);
                return ['code' => 200, 'data' =>"", 'msg' => '添加成功'];
            }else{
                return ['code' => 100, 'data' => '', 'msg' => '添加失败'];
            }
        }
        return $this->fetch('classroom/catalogueadd');
    }
    
    /**
     * 编辑章节
     * @return array|mixed
     */
    public function catalogueEdit(){
        set_time_limit (0);
        if(Request::instance()->isAjax()){
            $params = input('param.');
            $data = [
                'catalogue_title' => $params['catalogue_title'],//标题
//                'catalogue_img' => $params['images'],//缩略图
//                'catalogue_url' => "http://qiniu.verynurse.com/" . "h264_" . $qnInfo['key'],//视频
//                'classroom_id' => session('classroom_id'),//课程ID
//                'create_time' => date('Y-m-d H:i:s'),//创建时间
//                'catalogue_time' => $fen . ':' . $miao//视频时长
            ];
            //删除了原视频，但是没有删除新视频
            if(empty($params['photo']) && $params['del'] != ''){
                return ['code' => 100, 'data' => '', 'msg' => '请添加新视频'];
            }
            //删除了原视频，添加了新视频
            if($params['del'] != '' && $params['photo'] != ''){
                $filePath = $_SERVER['DOCUMENT_ROOT']. DS . trim($params['photo'], ',');
                $qnInfo = $this->videoQN($filePath);
                if($qnInfo){
                    $this->zhuanma($qnInfo['key']);
                }
                $time = explode('.', $qnInfo['vtime']);
                $fen = floor($time[0]/60);
                $miao = floor(($time[0]-$fen*60)%60);
                $data['catalogue_url'] = "http://qiniu.verynurse.com/" . "h264_" . $qnInfo['key'];//视频地址
                $data['catalogue_time'] = $fen . ':' . $miao;//视频时长
                @unlink($filePath);//删除本地文件
            }
            //更换了新的缩略图
            if(!empty($params['images'])){
                $data['catalogue_img'] = $params['images'];
            }
            $res = Db::table('up_classroom_catalogue')->where('catalogue_id', $params['catalogue_id'])->update($data);
            if($res){
                //编辑成功，重新提交审核
                Db::table('up_classroom')
                    ->where('id', session('classroom_id'))
                    ->setField('classroom_status', 1);
                return ['code' => 200, 'data' =>"", 'msg' => '编辑成功'];
            }else{
                return ['code' => 100, 'data' => '', 'msg' => '编辑失败'];
            }
        }
        $param = input('param.');
        $catalogue_id = $param['id'];
        $list = Db::table('up_classroom_catalogue')->where('catalogue_id', $catalogue_id)->find();
        $this->assign([
            'list' => $list,
            'catalogue_id' => $catalogue_id
        ]);
        return $this->fetch('classroom/catalogueedit');
    }
    
    /**
     * 上传文件到七牛
     * @param $filePath
     * @return mixed
     */
    public function videoQN($filePath)
    {
        set_time_limit (0);
        $accessKey = config('qiniu')['accessKey'];
        $secretKey = config('qiniu')['secretKey'];
        $bucket = config('qiniu')['bucket'];
        $auth = new Auth($accessKey, $secretKey);
        $key = date('YmdHis') . rand(100000, 999999) . '.mp4';//上传到七牛后的文件名称
        $returnBody = '{"key":"$(key)","vtime":"$(avinfo.video.duration)"}';//获取视频时长
        $policy = array(
            'returnBody' => $returnBody
        );
        $expires = 3600;
        $token = $auth->uploadToken($bucket, null, $expires, $policy, true);// 生成上传 Token
        $uploadMgr = new UploadManager();// 初始化 UploadManager 对象并进行文件的上传。
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);// 调用 UploadManager 的 putFile 方法进行文件的上传。
        if($err !== null) {
            $res = $err;
        } else {
            $res = $ret;
        }
        return $res;
    }
    
    /**
     * 转码
     * @param $key
     */
    public function zhuanma($key){
        set_time_limit (0);
        $accessKey = config('qiniu')['accessKey'];
        $secretKey = config('qiniu')['secretKey'];
        $bucket = config('qiniu')['bucket'];
        $auth = new Auth($accessKey, $secretKey);
        $pipeline = 'nandinggeer';//多媒体队列名
        $force = false;
        //转码完成后通知到你的业务服务器。
//        $notifyUrl = '= 'http://cjtdcms.xuanwumobile.com/super#advert_manage';
        
        $config = new \Qiniu\Config();
        $pfop = new PersistentFop($auth, $config);
        $fops = "avthumb/mp4/vcodec/libx264|saveas/" . \Qiniu\base64_urlSafeEncode($bucket .  ":" . 'h264_' . $key);
        list($id, $err) = $pfop->execute($bucket, $key, $fops, $pipeline, '', $force);
        if($err !== null) {
            $res = $err;
        } else {
            $res = $id;
        }
    }
}